import React, { useState, useEffect } from 'react';

import {NavBar, Icon, List, InputItem, Picker, ImagePicker, TextareaItem, Button, Toast, WhiteSpace} from 'antd-mobile';

import { createForm } from 'rc-form'

import { sexList, grades, R, MAX_LENGTH_PHOTO } from '@/assets/js/dict.js'
import { uploadPict, previewPict, deleteFile } from "@/api/login";
import { PostAddStudent, PostUpdateStudent, getStudentDetails } from "@/api/parent/chilDinformation.js"

import './student.scss';


let reImgObj = []; // 学生证照片 imgObj
let reId = []; // 学生证照片 id

function Student (props) {
    const [StudentInfoForm, SetStudentInfoForm] = useState({})

    const [pict, setPict] = useState([]);

    let handleOk = () => {
        console.log('props ------>>>', props)
        let postData = {};
        postData = props.form.getFieldsValue().StudentInfoForm
        console.log('StudentInfoForm ------->>>', postData);
        postData.gender = String(postData.gender);
        if (!!postData.grade) {
            postData.grade = postData.grade[0];
        }

        if (pict.length === 0) {
            Toast.info("检测到学生证照片未上传图片，请完善注册信息");
            return;
        } else if (pict.length < 2) {
            Toast.info("检测到学生证照片未上传完整，请完善注册信息");
            return;
        } else {
            postData.paper_pict = reId.join(',');
        }


        let student_id = sessionStorage.getItem("student_id");
        if (!!student_id) {
            postData.id = student_id;
            PostUpdateStudent(postData, (res) => {
                if (R.isSuccess(res)) {
                    Toast.success('操作成功', 2, () => {
                        props.history.goBack();
                    })
                }
            });
        } else {
            // 用户ID
            postData.parent_id = JSON.parse(sessionStorage.getItem('userInfo')).id;
            PostAddStudent(postData).then(res => {
                if (res.code == '000000') {
                    Toast.success(`${postData.name} 信息添加成功`, 1, () => {
                        sessionStorage.removeItem("student_id");
                        props.history.push("/studentList");
                    });
                }
            }).catch(err => {
                console.error(err);
            })
        }


    };

    function getStudent () {
        let id = sessionStorage.getItem("student_id");
        if (!!id) {
            getStudentDetails({ student_id: id }).then(res => {
                if (res.code == '000000') {
                    console.log('res -------->>>', res);
                    let data = res.responseData;
                    SetStudentInfoForm(data);
                    if (data.paper_pict) {
                        let imgFileObj = [];
                        data.paper_pict.split(',').map(item => {
                            imgFileObj.push({
                                file_id: item,
                                url: previewPict(item)
                            })
                        })

                        reImgObj = imgFileObj;
                        reId = (data.paper_pict).split(',')
                        setPict(imgFileObj);
                    }
                }
            }).catch(err => {
                console.error(err);
            })
        }
    }

    useEffect(getStudent, []);

    /**
     * 压缩图片
     *@param img 被压缩的img对象
     * @param type 压缩后转换的文件类型
     * @param mx 触发压缩的图片最大宽度限制
     * @param mh 触发压缩的图片最大高度限制
     */
    function compressImg (img, type, mx, mh) {
        return new Promise((resolve, reject) => {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            const { width: originWidth, height: originHeight } = img;
            // 最大尺寸限制
            const maxWidth = mx;
            const maxHeight = mh;
            // 目标尺寸
            let targetWidth = originWidth;
            let targetHeight = originHeight;
            if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > 1) {
                    // 宽图片
                    targetWidth = maxWidth;
                    targetHeight = Math.round(maxWidth * (originHeight / originWidth))
                } else {
                    // 高图片
                    targetHeight = maxHeight;
                    targetWidth = Math.round(maxHeight * (originWidth / originHeight))
                }
            }
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            context.clearRect(0, 0, targetWidth, targetHeight);
            // 图片绘制
            context.drawImage(img, 0, 0, targetWidth, targetHeight);
            canvas.toBlob(function (blob) {
                resolve(blob)
            }, type || 'image/png')
        })

    }

    // 压缩前将file转换成img对象
    function readImg (file) {
        return new Promise((resolve, reject) => {
            const img = new Image()
            const reader = new FileReader()
            reader.onload = function (e) {
                img.src = e.target.result
            }
            reader.onerror = function (e) {
                reject(e)
            }
            reader.readAsDataURL(file)
            img.onload = function () {
                resolve(img)
            }
            img.onerror = function (e) {
                reject(e)
            }
        })
    }

    const compress = async function (file, type, mx = 1000, mh = 1000) {
        const img = await readImg(file);
        let blob = await compressImg(img, file.type, mx, mh);
        return blob;
    };

    let onChange = async function (files, type, index) {
        console.log(files, type, index);
        if (type === "add") {
            if (files.length > 0) {
                let f = files[files.length - 1].file;
                if (f.size >= MAX_LENGTH_PHOTO) {
                    Toast.info(`请选择小于${MAX_LENGTH_PHOTO/1048576}兆的图片`);
                    setPict([]);
                } else {
                    try {
                        const blob = await compress(f, f.type, 1000, 1000);
                        f = blob;
                    } catch (e) {
                        console.error("error 压缩图片异常---> ", e);
                    }
                    uploadPict({ file: f, note: "学生证照片" }, (res) => {
                        if (res[R.code] === R.success) {
                            reImgObj.push({ file_id: res[R.data], url: previewPict(res[R.data]) });
                            reId.push(res[R.data])
                            setPict([...reImgObj]);
                        }
                    });
                }
            }
        } else if (type === "remove") {
            deleteFile({
                id: pict[index].file_id
            }).then(res => {
                if (res.code === '000000') {
                    reImgObj.splice(index, 1)
                    reId.splice(index, 1)
                    setPict([...files]);
                }
            })
        } else {
            setPict([]);
            reImgObj = []; // 学生证照片 imgObj
            reId = []; // 学生证照片 id
        }
    };
    const { getFieldProps } = props.form;

    function back() {
        props.history.goBack();
    }

    return (
        <div className="student">
            <div className="page-title  student-tit">
                <NavBar
                    mode="light"
                    icon={<Icon type="left" />}
                    onLeftClick={back}
                >
                    学生信息
                </NavBar>
            </div>
            <div className="page-content student-content">
                <div className="student-content-piece">
                    <div className="form-box">
                        <div className="form-tit">
                            <i className="mini-block"/>
                            <strong>基本信息</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <InputItem
                                    {...getFieldProps('StudentInfoForm.name', {
                                        initialValue: StudentInfoForm.name
                                    })}
                                    clear
                                    placeholder="学生姓名"
                                >姓名</InputItem>
                                <WhiteSpace size="md" />
                                <Picker
                                    data={sexList}
                                    cols={1}
                                    {...getFieldProps('StudentInfoForm.gender', { initialValue: [StudentInfoForm.gender] })}

                                >
                                    <List.Item arrow="horizontal">性別</List.Item>
                                </Picker>
                                <WhiteSpace size="md" />
                                <Picker
                                    data={grades}
                                    cols={1}
                                    {...getFieldProps('StudentInfoForm.grade', { initialValue: [StudentInfoForm.grade] })}

                                >
                                    <List.Item arrow="horizontal">年级</List.Item>
                                </Picker>

                                <WhiteSpace size="md" />
                                <InputItem
                                    {...getFieldProps('StudentInfoForm.age', {
                                        initialValue: StudentInfoForm.age
                                    })}
                                    type="number"
                                    clear
                                    placeholder="年龄"
                                >年龄</InputItem>
                                <WhiteSpace size="md" />
                                <List.Item multipleLine>
                                    学生证照片（内容包括封面和信息页）
                                    <List.Item.Brief>
                                        <ImagePicker
                                            files={pict}
                                            onChange={onChange}
                                            selectable={pict.length < 2}
                                            multiple={false}
                                            accept="image/jpeg,image/jpg,image/png"
                                        />
                                    </List.Item.Brief>
                                </List.Item>
                            </List>
                        </div>
                        <div className="form-tit">
                            <i className="mini-block"/>
                            <strong>其他信息</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <InputItem
                                    editable={false}
                                    labelNumber="7"
                                >孩子情况简介</InputItem>

                                <TextareaItem
                                    {...getFieldProps('StudentInfoForm.note', {
                                        initialValue: StudentInfoForm.note
                                    })}
                                    placeholder="请输入"
                                    clear
                                    rows="6"
                                    autoHeight
                                    count={200}
                                />
                            </List>
                        </div>
                        <div className="form-footer">
                            <p className="notes">

                        </p>
                            <Button type="primary" onClick={handleOk}>确认</Button>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    );
}

Student = createForm()(Student);

export default Student;